<template>
    <div id="admin">
        <div id="admin-nav" :style="{width:mavWidth}" :class="setup.theme=='light'?'nav-light':'nav-dark'">
            <div id="logo" v-if="setup.showLogo">
                <div :class="setup.theme=='light'?'dark':'light'">
                    <a-avatar
                            :src="require('../../assets/logo.png')"
                    />
                    {{title}}
                </div>
            </div>
            <div>
                <a-menu
                        mode="inline"
                        :theme=setup.theme
                        :inline-collapsed="collapsed"
                        v-model:openKeys="openKeys"
                        v-model:selectedKeys="selectedKeys"
                >
                    <a-menu-item key="wel" @click="switchView('/admin','首页','欢迎')">
                        <PieChartOutlined/>
                        <span>首页</span>
                    </a-menu-item>
                    <a-sub-menu key="sub1">
                        <template #title>
                          <span>
                            <MailOutlined/>
                            <span>系统管理</span>
                          </span>
                        </template>
                        <a-menu-item @click="switchView('article','系统管理','文章管理')">文章管理</a-menu-item>
                        <a-menu-item @click="switchView('administrators','系统管理','用户管理')">用户管理</a-menu-item>
                        <a-menu-item @click="switchView('file','系统管理','资料管理')">资料管理</a-menu-item>
                    </a-sub-menu>
                    <a-sub-menu key="sub2">
                        <template #title>
                      <span>
                        <AreaChartOutlined/>
                        <span>系统监控</span>
                      </span>
                        </template>
                        <a-menu-item @click="switchView('making','系统监控','访客记录')">访客记录</a-menu-item>
                        <a-menu-item @click="switchView('making','系统监控','日志记录')">日志记录</a-menu-item>
                    </a-sub-menu>
                    <a-sub-menu key="sub3">
                        <template #title>
                      <span>
                        <SettingOutlined/>
                        <span>高级设置</span>
                      </span>
                        </template>
                        <a-menu-item @click="switchView('making','高级设置','网站设置')">网站设置</a-menu-item>
                        <a-menu-item @click="switchView('making','高级设置','恢复出厂设置')">恢复出厂设置</a-menu-item>
                    </a-sub-menu>
                </a-menu>
            </div>
        </div>
        <div id="admin-main" :style="{marginLeft:mainLeft}">
            <div id="admin-top" :style="{background:setup.topColor}">
                <a-row>
                    <a-col :span="12" style="padding-left: 10px;">
                        <div style="display: inline-block;">
                            <a-button class="dark" type="link" :style="{color:setup.topBtnColor}"
                                      @click="toggleCollapsed"
                                      style="margin-top: -10px;font-size: 18px;">
                                <MenuUnfoldOutlined v-if="collapsed"/>
                                <MenuFoldOutlined v-else/>
                            </a-button>
                        </div>
                        <div style="display: inline-block;">
                            <a-breadcrumb :style="{color:setup.topBtnColor}">
                                <template #separator><span :style="{color:setup.topBtnColor}">></span></template>
                                <a-breadcrumb-item v-show="breadcrumbA!=''">{{breadcrumbA}}</a-breadcrumb-item>
                                <a-breadcrumb-item v-show="breadcrumbB!=''" :style="{color:setup.topBtnColor}">
                                    {{breadcrumbB}}
                                </a-breadcrumb-item>
                            </a-breadcrumb>
                        </div>

                    </a-col>

                    <a-col :span="12" style="padding-right: 15px;">
                        <div style="float: right;">
                            <span class="top-btn" :style="{color:setup.topBtnColor}" @click="handleFullScreen">
                                <FullscreenOutlined v-if="!fullscreen"/>
                                <FullscreenExitOutlined v-else/>
                            </span>
                            <span class="top-btn" :style="{color:setup.topBtnColor}" @click="$router.go(0)">
                                <SyncOutlined/>
                            </span>
                            <span class="top-btn">
                                 <a-avatar
                                         style="position: relative;top: -2px;"
                                         :src="userInfo.user.head"
                                 />
                            </span>

                            <a-dropdown class="top-btn">
                                <a
                                        class="ant-dropdown-link" @click.prevent :style="{color:setup.topBtnColor}"
                                        style="font-size: 16px;">
                                    {{userInfo.user.nickname}}
                                    <DownOutlined/>
                                </a>
                                <template #overlay>
                                    <a-menu style="text-align: center;">
                                        <a-menu-item>
                                            <a href="javascript:;"
                                               @click="showModal">个人信息</a>
                                        </a-menu-item>
                                        <a-menu-item>
                                            <a href="javascript:;"
                                               @click="selfSwitchView('resetPassword','个人设置','修改密码')">修改密码</a>
                                        </a-menu-item>
                                        <a-menu-item>
                                            <a href="javascript:;" @click="logout">退出登录</a>
                                        </a-menu-item>
                                    </a-menu>
                                </template>
                            </a-dropdown>
                            <span class="top-btn dark" :style="{color:setup.topBtnColor}" @click="showDrawer">
                                  <MoreOutlined/>
                            </span>
                        </div>
                        <div style="clear: both;"></div>
                    </a-col>
                </a-row>
            </div>
            <div id="admin-view">
                <router-view id="rv"/>
            </div>
        </div>
    </div>
    <a-drawer
            id="setup"
            title="设置"
            placement="right"
            :closable="false"
            v-model:visible="visible"
            :after-visible-change="afterVisibleChange"
    >
        <div class="mb-2">
            <a-row>
                <a-col :span="16">
                    主题模式
                </a-col>
                <a-col :span="8" style="text-align: right;">
                    <a-switch
                            checked-children="亮"
                            un-checked-children="黑"
                            v-model:checked="setup.themeCheck"/>
                </a-col>
            </a-row>
        </div>
        <div class="mb-2">
            <a-row>
                <a-col :span="16">
                    显示Logo
                </a-col>
                <a-col :span="8" style="text-align: right;">
                    <a-switch
                            v-model:checked="setup.showLogo"/>
                </a-col>
            </a-row>
        </div>
        <div class="mb-2">
            <a-row>
                <a-col :span="16">
                    主题配色
                </a-col>
                <a-col :span="8" style="text-align: right;">
                    <a-select
                            v-model:value="setup.topColorText"
                            ref="select"
                            @change="handleChange"
                    >
                        <a-select-option value="默认">
                            <input class="color" type="color" value="#ffffff" disabled/>
                        </a-select-option>
                        <a-select-option value="时尚">
                            <input class="color" type="color" value="#1e9fff" disabled/>
                        </a-select-option>
                        <a-select-option value="激情">
                            <input class="color" type="color" value="#ffa600" disabled/>
                        </a-select-option>
                        <a-select-option value="运动">
                            <input class="color" type="color" value="#ff3e57" disabled/>
                        </a-select-option>
                    </a-select>
                </a-col>
            </a-row>
        </div>
        <div class="mb-2">
            <a-row>
                <a-col :span="4">
                    图床
                </a-col>

                <a-col :span="4">
                    <div>
                        <input type="text" id="imgPath" style="width: 1px;border: none;outline: none;color: #ffffff;">
                    </div>
                </a-col>
                <a-col :span="16" style="text-align: right;">
                    <a-upload
                            name="file"
                            :multiple="false"
                            :action="uploadPath"
                            :headers="headers"
                            :showUploadList="false"
                            @change="uploadImage"
                            :before-upload="beforeUpload"
                    >
                        <a-button>
                            <upload-outlined></upload-outlined>
                            上传
                        </a-button>
                    </a-upload>
                </a-col>
            </a-row>
        </div>
    </a-drawer>
    <a-modal v-model:visible="selfVisible"
             title="个人信息"
             okText="确定"
             cancelText="取消"
             @ok="handleOk"

    >
        <p>
            用户头像：
            <a-avatar
                    style="position: relative;top: -2px;"
                    :src="selfUser.head"
            />
            &nbsp;
            <a-upload
                    name="file"
                    :multiple="false"
                    :action="uploadPath"
                    :headers="headers"
                    :showUploadList="false"
                    @change="updateHead"
                    :before-upload="beforeUpload"
            >
                <a-button size="small">
                    <upload-outlined></upload-outlined>
                </a-button>
            </a-upload>
        </p>
        <p>用户昵称：<input type="text" style="border: none;outline: none;" v-model="selfUser.nickname"
                       @blur="updateNickName"></p>

        <p>登录名称：{{selfUser.username}}</p>
        <p>登录密码：******
            <a href="javascript:void(0)" style="font-size: 12px;"
               @click="selfSwitchView('resetPassword','个人设置','修改密码')">[修改]</a>
        </p>
        <p>电子邮箱：123456789@qq.com</p>
        <p>创建日期：{{selfUser.created}}</p>

        <div>
            角色权限：
            <span v-for="role in selfUser.roles">
                    <a-tag color="#f50" v-if="role.role=='ROLE_ADMIN'">管理员</a-tag>
                    <a-tag color="#2db7f5" v-if="role.role=='ROLE_NONE'">用户</a-tag>
            </span>
        </div>

    </a-modal>
</template>
<script>
    import {
        defineComponent,
        reactive,
        toRefs,
        watch,
        getCurrentInstance,
        onMounted,
        onBeforeMount,
        onBeforeUnmount,
        createVNode
    } from 'vue';
    import {useRouter, useRoute} from 'vue-router'
    import {
        MenuFoldOutlined,
        MenuUnfoldOutlined,
        PieChartOutlined,
        MailOutlined,
        DesktopOutlined,
        InboxOutlined,
        AreaChartOutlined,
        MoreOutlined,
        SyncOutlined,
        FullscreenOutlined,
        FullscreenExitOutlined,
        DownOutlined,
        SettingOutlined,
        UploadOutlined,
        ExclamationCircleOutlined
    } from '@ant-design/icons-vue';

    import {message, Modal, notification} from "ant-design-vue"
    import {getUserInfo, parseDatetime} from "../../utils/util";
    import {getUserById, renameNickName, updateHead as updateHeadApi} from "../../api/admin";

    export default defineComponent({
        name: "admin",
        components: {
            MenuFoldOutlined,
            MenuUnfoldOutlined,
            PieChartOutlined,
            MailOutlined,
            DesktopOutlined,
            InboxOutlined,
            AreaChartOutlined,
            MoreOutlined,
            SyncOutlined,
            FullscreenOutlined,
            FullscreenExitOutlined,
            DownOutlined,
            SettingOutlined,
            UploadOutlined,
            ExclamationCircleOutlined
        },
        setup() {
            //响应式数据
            const state = reactive({
                title: "星时代联盟",
                userInfo: "",
                collapsed: false,
                selectedKeys: ['wel'],
                openKeys: [],
                preOpenKeys: [],
                visible: false,
                fullscreen: false,
                mavWidth: "15vw",
                mainLeft: "15vw",
                setup: {
                    showLogo: true,
                    theme: "dark",//主题
                    themeCheck: false,
                    topColor: "#fff",//背景颜色
                    topColorText: "默认",//字体主题
                    topBtnColor: "#6b6b6bb3",//文字颜色
                },
                breadcrumbA: "首页",
                breadcrumbB: "欢迎",
                selfVisible: false,
                selfUser: {},
                headers: {
                    token: ""
                },
                uploadPath: "",
                updateHeadPath: ""
            });
            //主题
            const colorText = ["默认", "时尚", "激情", "运动"]
            //背景颜色
            const color = ["#fff", "#1e9fff", "#ffa600", "#ff3e57"]
            //文字颜色
            const textColor = ["#6b6b6bb3", "#fff", "#fff", "#fff"]
            const handleChange = topColorText => {
                for (let i in colorText) {
                    if (colorText[i] == topColorText) {
                        state.setup.topColor = color[i]
                        state.setup.topBtnColor = textColor[i]
                    }
                }
                message.success("已修改")
                settingDao();
            };
            const router = useRouter();
            const route = useRoute();
            const toggleCollapsed = () => {
                if (state.collapsed) {
                    state.title = "星时代联盟"
                    state.mavWidth = "15vw";
                    state.mainLeft = "15vw";
                } else {
                    state.title = "爪哇"
                    state.mavWidth = "80px";
                    state.mainLeft = "80px";
                }
                state.collapsed = !state.collapsed;
                state.openKeys = state.collapsed ? [] : state.preOpenKeys;
            };
            const afterVisibleChange = bool => {
                console.log('visible', bool);
            };
            const showDrawer = () => {
                state.visible = true;
            };
            //全屏切换
            const handleFullScreen = () => {
                let element = document.documentElement;
                if (state.fullscreen) {
                    if (document.exitFullscreen) {
                        document.exitFullscreen();
                    } else if (document.webkitCancelFullScreen) {
                        document.webkitCancelFullScreen();
                    } else if (document.mozCancelFullScreen) {
                        document.mozCancelFullScreen();
                    } else if (document.msExitFullscreen) {
                        document.msExitFullscreen();
                    }
                } else {
                    if (element.requestFullscreen) {
                        element.requestFullscreen();
                    } else if (element.webkitRequestFullScreen) {
                        element.webkitRequestFullScreen();
                    } else if (element.mozRequestFullScreen) {
                        element.mozRequestFullScreen();
                    } else if (element.msRequestFullscreen) {
                        // IE11
                        element.msRequestFullscreen();
                    }
                }
                state.fullscreen = !state.fullscreen;
            }
            //注销
            const logout = () => {
                sessionStorage.clear();
                router.replace("/login");
                message.success("退出成功");
            }
            //主题配置持久化
            const settingDao = () => {
                const setting = JSON.stringify(state.setup);
                localStorage.setItem("setting", setting);
            }
            //路由跳转
            const switchView = (path, a, b) => {
                //a是一级目录，b是二级目录
                state.breadcrumbA = a || '';
                state.breadcrumbB = b || '';
                //动画效果
                //state.mainTop = "100px";
                router.push(path);
                // setTimeout(() => {
                //     state.mainTop = 0;
                // }, 1)
                if (state.selfVisible) {
                    state.selfVisible = false;
                }
            }
            //右侧下拉菜单路由跳转
            const selfSwitchView = (path, a, b) => {
                state.selectedKeys = [];
                switchView(path, a, b);
            }


            const showModal = () => {
                const id = getUserInfo().user.id;
                state.selfVisible = true;
                getUserById(id).then(resp => {
                    state.selfUser = resp.data
                    console.log(state.selfUser)
                    state.selfUser.created = parseDatetime(state.selfUser.created)
                    if (!state.selfUser.head.startsWith("http")) {
                        state.selfUser.head = window.apiPath + state.selfUser.head;
                    }
                })
            };

            const handleOk = e => {
                state.selfVisible = false;
            };

            const updateNickName = () => {
                if (state.selfUser.nickname == "" ||
                    state.selfUser.nickname == state.userInfo.user.nickname
                ) {
                    return false;
                }
                renameNickName(state.selfUser.nickname).then(resp => {
                    message.success("昵称修改" + resp.message)
                    state.userInfo.user.nickname = state.selfUser.nickname
                })
            }

            const welcome = () => {
                let d = new Date();
                let desc = "";
                let hours = d.getHours()
                if (hours < 6) {
                    desc = "夜深了，请注意休息！"
                } else if (hours < 12) {
                    desc = "早上好！"
                } else if (hours < 18) {
                    desc = "下午好！"
                } else {
                    desc = "晚上好！"
                }
                desc += "管理员。欢迎登录使用本系统。在使用过程中如有任何疑问，请联系超级管理员。"
                notification.success({
                    message: '欢迎',
                    description: desc,
                    duration: "10"
                })
            }

            const uploadImage = info => {
                const status = info.file.status;
                if (status !== 'uploading') {
                    //console.log(info.file, info.fileList);
                }
                if (status === 'done') {
                    if (info.file.response.code === 200) {
                        var path = window.apiPath + info.file.response.data.relativePath;
                        message.success(`${info.file.name} 文件上传成功.`);
                        Modal.success({
                            title: "图片上传成功",
                            content: "图片地址：\n" + path,
                            centered: false,
                            okText: "复制",
                            closable: true,
                            maskClosable: true,
                            onOk() {
                                var input = document.getElementById("imgPath");
                                input.value = path; // 修改文本框的内容
                                console.log(input.value)
                                input.select(); // 选中文本
                                if (document.execCommand('copy')) {
                                    document.execCommand('copy');
                                    message.success('复制成功');
                                } else {
                                    message.error('你的浏览器不支持自动复制');
                                }
                            }
                        })


                    } else {
                        message.error(`${info.file.name} 文件上传失败.`);
                        Modal.error({
                            title: "错误:上传失败!",
                            content: "失败原因：" + info.file.response.message,
                            centered: false,
                            okText: "确定"
                        })
                    }
                } else if (status === 'error') {
                    message.error(`${info.file.name} 文件上传失败.`);
                    Modal.error({
                        title: "错误",
                        content: "上传失败",
                        centered: false,
                        okText: "确定"
                    })
                }
            }

            const beforeUpload = file => {
                const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/gif';
                let msg = "";
                if (!isJpgOrPng) {
                    msg = "系统规定只能上传图片文件！而上传的文件类型为：" + file.type;
                }
                const isLt5M = file.size / 1024 / 1024 < 5;

                if (!isLt5M) {
                    msg = "图片大小不能大于 5MB！"
                }

                if (msg != "") {
                    Modal.error({
                        title: "错误",
                        content: "检测到你上传的文件非法！ \n 具体原因：" + msg + "。",
                        centered: false,
                        okText: "确定"
                    })
                }
                return isJpgOrPng && isLt5M;
            };

            const updateHead = (info) => {
                const status = info.file.status;
                if (status !== 'uploading') {
                    //console.log(info.file, info.fileList);
                }
                if (status === 'done') {
                    if (info.file.response.code === 200) {
                        var path = info.file.response.data.relativePath;
                        message.success(`图片上传成功.`);
                        //开始把图片路径给用户
                        updateHeadApi(path).then(resp => {
                            console.log(resp)
                            if (resp.code == 200) {
                                message.success(`头像修改成功.`);
                                state.selfUser.head = window.apiPath + path;
                                state.userInfo.user.head = state.selfUser.head;
                                sessionStorage.setItem("userInfo", JSON.stringify(state.userInfo));
                            } else {
                                message.error(`头像修改失败.`);

                            }
                        })

                    } else {
                        message.error(`${info.file.name} 图片上传失败.`);
                        Modal.error({
                            title: "错误:上传失败!",
                            content: "失败原因：" + info.file.response.message,
                            centered: false,
                            okText: "确定"
                        })
                    }
                } else if (status === 'error') {
                    message.error(`${info.file.name} 图片上传失败.`);
                }
            }

            onBeforeMount(() => {
                const setting = JSON.parse(localStorage.getItem("setting"));
                if (setting != null) {
                    state.setup = setting;
                }
                state.userInfo = getUserInfo();
                if (!state.userInfo.user.head.startsWith("http")) {
                    state.userInfo.user.head = window.apiPath + state.userInfo.user.head;
                }
                welcome();
            })
            onBeforeUnmount(() => {
                settingDao();
            })

            onMounted(() => {
                window.addEventListener('beforeunload', () => {
                    settingDao();
                });
                if (window.screen.width < 1100) {
                    toggleCollapsed();
                }
                state.mainTop = 0;
                state.uploadPath = window.apiPath + "/file/imageUpload"
                state.headers.token = getUserInfo().token;
            });

            watch(() => state.setup.themeCheck,
                (val, oldVal) => {
                    state.setup.theme = val ? "light" : "dark";
                },
            );
            //下拉菜单
            watch(() => state.openKeys,
                (val, oldVal) => {
                    state.preOpenKeys = oldVal;
                },
            );


            return {
                ...toRefs(state),
                toggleCollapsed,
                afterVisibleChange,
                showDrawer,
                handleFullScreen,
                logout,
                handleChange,
                switchView,
                selfSwitchView,
                showModal,
                handleOk,
                updateNickName,
                uploadImage,
                beforeUpload,
                updateHead
            };
        },

    });
</script>
<style scoped lang="less">

    #admin {
        position: relative;
        height: 100vh;
        overflow: hidden;

        #admin-nav {
            overflow: auto;
            height: 100vh;
            width: 15vw;
            transition: width 0.1s;

            #logo {
                color: #ffffff;
                user-select: none;
                font-size: 18px;
                text-align: center;
                padding: 15px;
                font-weight: 400;
                font-family: 华文新魏, serif;
            }
        }

        #admin-main {
            position: absolute;
            right: 0;
            top: 0;
            left: 0;
            margin-left: 15vw;
            height: 100vh;
            overflow: hidden;
            background-color: #f2f2f2;
            transition: margin-left 0.1s;

            #admin-top {
                height: 55px;
                background-color: #ffffff;
                box-shadow: 5px 0 10px darkgrey;
                font-size: 22px;
                box-sizing: border-box;
                line-height: 50px;

                .top-btn {
                    font-size: 16px;
                    display: inline-block;
                    margin-right: 20px;
                    cursor: pointer;
                    color: #6b6b6bb3;
                }
            }

            #admin-view {
                background-color: #f2f2f2;
                height: 100%;
            }
        }

    }

    .nav-light {
        background-color: #ffffff;

    }

    .nav-dark {
        background-color: #001529;
    }

    .light {
        color: #ffffff;
    }

    .dark {
        color: #001529;
    }

    .mb-2 {
        margin-bottom: 15px;
    }

    #rv {
        padding: 15px;
        margin: 10px;
        overflow-x: hidden;
        overflow-y: auto;
        height: 90vh;
    }

    .color {
        margin: 4px auto;
        width: 20px;
        border: 1px solid darkgrey;
    }
</style>